<?php
require_once('Model/SiteManage.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
class Model_Item
{
    private   $sys;
    public    $config;
    protected $table_name;
    protected $setting_table_name;
    protected $category_table_name;
    protected $company_table_name;

    public function __construct()
    {
        $this->sys        = new Model_SiteManage();
        $config           = __get_config('plugin.ini');
        
        $this->config     = $config['MANAGE_ITEM'];
        $this->table_name          = 'M_ITEM';
        $this->setting_table_name  = 'D_ITEM_SETTING';
        $this->category_table_name = 'D_ITEM_CATEGORY';
        $this->company_table_name  = 'R_COMPANY';
    }
    //
    public function insert($data)
    {
        $db = new Model_DB();
        if(!isset($data['site_id'])){
            $data['site_id'] = $this->sys->getCurrentSite();
        }
        return $db->insert($this->table_name, $data);
    }
    public function update($id, $data)
    {
        $db = new Model_DB();
        return $db->update($id, $this->table_name, $data);
    }
    public function get($id)
    {
        $db = new Model_DB();
        $sql = sprintf("select * from ".$this->table_name." where site_id = %d and id = %d", $this->sys->getCurrentSite(), $db->escape($id));
        $db->query($sql);
        return $db->fetch();
    }
    public function delete($id)
    {
        $db   = new Model_DB();
        $data = array();
        $data['id']      = $id;
        $data['site_id'] = $this->sys->getCurrentSite();
        return $db->delete($this->table_name, $data);
    }
    public function getListCount($data)
    {
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select count(*) from {$this->table_name}";
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "");
        $db->query($sql);
        if ($db->res){
            return array_shift($res = $db->fetch());
        }
        return false;
    }
    public function getList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {
        $list  = array();
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select * from {$this->table_name}";
        $sql  .= (!empty($where) ? " where " . implode(' AND ', $where) : "") . (!empty($orderby) ? " order by {$orderby}" : "") . (!empty($limit) ? " limit {$limit}" : "") . (!empty($offset) ? " offset {$offset}" : "");
        $db->query($sql);
        if ($db->res){
            while($res = $db->fetch()){
                if(isset($res['id'])){
                    $list[$res['id']] = $res;
                }
                else{
                    $list[] = $res;
                }
            }
        }
        return $list;
    }
    private function createSearchCondition($data, $prefix = '')
    {
        $db    = new Model_DB();
        $where = array();
        if ($prefix != ''){
            $prefix = $prefix . '.';
        }
        if(!isset($data['site_id'])){
            $where[] = "{$prefic}site_id = {$this->sys->getCurrentSite()}";
        }
        else{
            $where[] = '1 = 1';
        }
        foreach($db->getFieldList($this->table_name) as $key => $_){
            if (isset($data[$key]) && $data[$key] !== ''){
                
                if(is_array($data[$key]))//データが配列の場合
                {
                    foreach($data[$key] as $one)
                    {
                        $value = $db->escape($one);
                        $tmp[$key][] = "{$prefix}{$key} = '{$value}'";
                    }
                    $where[] = implode(" OR ", $tmp[$key]);
                }
                else
                {
                    $value = $db->escape($data[$key]);
                    if ($key == 'title'){
                        $where[] = "{$prefix}{$key} collate utf8_unicode_ci like '%{$value}%'";
                    }else{
                        $where[] = "{$prefix}{$key} = '{$value}'";
                    }
                }
            }
        }
        return $where;
    }
    public function validate(&$data, &$err)
    {
        $validate = new Model_Validate();
        // required
        $keys = explode(',', 'status,item_name');
        foreach($keys as $key){
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key]['NotEmpty'] = true;
            }
        }
        //数字かどうかチェック
        $keys = explode(',', 'order_num,cost,price,price2,special_price');
        foreach($keys as $key){
            if(isset($data[$key]) and $data[$key]!=''){
                if ($validate->Int($data[$key])){
                    $err[$key]['Int'] = true;
                }
            }
        }        
        return empty($err);
    }
    public function getCategory($item_id)
    {
        $db  = new Model_DB();
        $sql = sprintf("select * from {$this->category_table_name} where item_id = %d order by sort_order asc", $item_id);
        $db->query($sql);
        $category = array();
        while($res = $db->fetch()){
            $category[] = $res['category_id'];
        }
        return $category;
    }
    public function updateCategory($item_id, $category)
    {
        $db = new Model_DB();
        $db->delete($this->category_table_name, array('item_id' => $item_id));
        $sort_order = 0;
        foreach($category as $category_id){
            $sort_order ++;
            $data                = array();
            $data['item_id']     = $item_id;
            $data['category_id'] = $category_id;
            $data['sort_order']  = $sort_order;
            $db->insert($this->category_table_name, $data);
        }
    }
    
    public function updateCompany($category)
    {
        $db = new Model_DB();
        $sql = sprintf("DELETE FROM ".$this->company_table_name." WHERE func = %u ", $this->config['id'] );
        $db->query( $sql );
        foreach($category as $category_id){
            if($category_id != '')
            {
                $data             = array();
                $data['func']     = $this->config['id'];
                $data['category'] = $category_id;
                $db->insert($this->company_table_name, $data);
            }
        }
    }
    
    public function registItemImage($item_id, $image)
    {
        // 画像登録
        /*
                商品（大）			240*160
                商品（小）			120*80
        */
        $db  = new Model_DB();
        $sql = sprintf("DELETE FROM D_IMAGE WHERE func = %u and id = %u", $this->config['id'], $item_id );
        $db->query( $sql );

        $uploader  = new Model_Uploader();
        foreach( $image as $num => $one ){
            if( $one[0] != '' ){
                $cache = $one[0];

                //仮で画像保存
                $base_name = 'tmp_'. $item_id . '_' . $num;
                $move_to   = $this->getThumbDir();
                $tmp_filename  = $uploader->moveCacheImage($cache, $move_to, $base_name);

                //拡張子取得
                $tmp = explode('.', $tmp_filename );
                $ext = '.' . end( $tmp );


                //メイン
                $filename = $item_id . '_' . $num . $ext;
                $this->resize( $move_to.$tmp_filename, $move_to.$filename, 320, 216 );

                //サムネイル
                $thumb_filename = 'thumb_' . $item_id . '_' . $num . $ext;           
                $this->resize( $move_to.$tmp_filename, $move_to.$thumb_filename, 215, 160 );

                //tmpファイル削除
                unlink($move_to.$tmp_filename);
                
                $sql = sprintf( "INSERT INTO D_IMAGE( func, id, order_num, filename, thumb ) VALUES( %u, %u, %u, '%s', '%s' )",
                        $this->config['id'],
                        $item_id,
                        $num,
                        $filename,
                        $thumb_filename
                );
                $db->query( $sql );
            }
        }
    }
    //
    public function getSetting($site_id = '')
    {
        if ($site_id == ''){
            $site_id = $this->sys->getCurrentSite();
        }
        $db  = new Model_DB();
        $sql = "select * from {$this->setting_table_name} where site_id = {$site_id}";
        $db->query($sql);
        $setting = array();
        if ($db->num_rows() > 0){
            $setting = $db->fetch();
            $setting['top_items']  = explode(',', $setting['top_items']);
            $setting['list_items'] = explode(',', $setting['list_items']);
        }
        else{
            // default values
            $setting['top_nums']   = 3;
            $setting['top_items']  = array('date','title');
            $setting['list_nums']  = 10;
            $setting['list_items'] = array('date','title');
            $setting['sort_item']  = 'date';
        }
        return $setting;
    }
    public function validateSetting(&$data, &$err)
    {
        $validate = new Model_Validate();
        // required
        $keys = explode(',', 'content_name,category_id,select_category');
        foreach($keys as $key){
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key]['NotEmpty'] = true;
            }
        }
        
        foreach($data['select_category'] as $one)
        {
            if($one == "")
            {
                $err['select_category']['NotEmpty'] = true;
            }
        }
        
        return empty($err);
    }
    public function updateSetting($data, $site_id = '')
    {
        if ($site_id == ''){
            $site_id = $this->sys->getCurrentSite();
        }
        $data['site_id'] = $site_id;
        $db = new Model_DB();
        $db->replace($this->setting_table_name, $data);
    }
    //　状態
    public function getStatusMap()
    {
        $map    = array();
        $map[2] = '仮登録';
        $map[1] = '公開';
        $map[0] = '非公開';
        return $map;
    }
    //　表示項目
    public function getDisplayItemsMap()
    {
        $map    = array();
        $map[code]          = 'コード';
        $map[item_name]     = '商品名';
        $map[thumb]         = 'サムネイル画像';
        $map[producing_area] = '生産地';
        return $map;
    }
    //　時間
    public function getTimeMap()
    {
        for($i=0; $i<24; $i++)
        {
            $map[$i] = $i;
        }
        return $map;
    }
    //　表示順
    public function getSortMap()
    {
        $map    = array();
        $map[order_num] = '優先順位（降順）';
        $map[u_date] = '最終更新日時順（降順）';
        $map[item_kana] = '五十音順';
        $map[price] = '価格順（昇順）';
        return $map;
    }
    //企業マスタ
    public function getCompany()
    {
	$company = array();
        $config = __get_config('plugin.ini');
        $db  = new Model_DB();
	$sql = sprintf( "SELECT MC.id, MC.company_name FROM M_COMPANY MC, R_CATEGORY RC WHERE MC.site = %u AND MC.id = RC.id AND RC.func = %u AND RC.category IN( SELECT category FROM R_COMPANY WHERE func = %u )", $this->sys->getCurrentSite(), $config["MANAGE_COMPANY"]["id"], $this->config['id'] );
        $db->query( $sql );
	while( $row = $db->fetch() ){
            $company[ $row['id'] ] = $row['company_name'];
	}
        return $company;
    }
    //生産地
    public function getProducingAreaMap()
    {
        $values = array(
            '北海道','青森県','岩手県','宮城県','秋田県','山形県','福島県','茨城県','栃木県','群馬県',
            '埼玉県','千葉県','東京都','神奈川県','新潟県','富山県','石川県','福井県','山梨県','長野県',
            '岐阜県','静岡県','愛知県','三重県','滋賀県','京都府','大阪府','兵庫県','奈良県','和歌山県',
            '鳥取県','島根県','岡山県','広島県','山口県','徳島県','香川県','愛媛県','高知県','福岡県',
            '佐賀県','長崎県','熊本県','大分県','宮崎県','鹿児島県','沖縄県',
        );
        foreach($values as $v)
        {
            $map[$v] = $v;
        }
        return $map;
    }
    
    //
    public function getFormKeys()
    {
        $db = new Model_DB();
        return array_keys($db->getFieldList($this->table_name));
    }
    //
    public function getThumbDir($mkdir = true)
    {
        $thumb_dir = $this->sys->getCurrentSiteDir() . '/' . $this->config['thumb_dir'];
        if ($mkdir == true){
            $this->sys->createDir($thumb_dir);
        }
        //return SiteManageRootDir . '/htdocs/' . $thumb_dir;
        return $thumb_dir;
    }
    public function getThumbUrl()
    {
        return $this->sys->getCurrentSiteUrl() . '/' . $this->config['thumb_dir'];
    }
    public function getFileDir($mkdir = true)
    {
        $file_dir = $this->sys->getCurrentSiteDir() . '/' . $this->config['file_dir'];
        if ($mkdir == true){
            $this->sys->createDir($file_dir);
        }
        return SiteManageRootDir . '/htdocs/' . $file_dir;
    }
    
    // 画像リサイズ・保存
    function resize( $src, $dest, $new_width, $new_height ){

            if( !file_exists($src) ) return false;

            if( eregi( ".jpg$", $dest ) ){
                    $type = "jpeg";
            }elseif( eregi( ".jpeg", $dest ) ){
                    $type = "jpeg";
            }elseif( eregi( ".png", $dest ) ){
                    $type = "png";
            }elseif( eregi( ".gif", $dest ) ){
                    $type = "gif";
            }else{
                    $type = "";
            }

            if( $srcSize = getImageSize( $src ) ){
                    $srcWidth  = $srcSize[0];
                    $srcHeight = $srcSize[1];

                    if( $type == "jpeg" ){
                            $srcImage = imageCreateFromJpeg( $src );
                    }elseif( $type == "png" ){
                            $srcImage = imageCreateFromPng( $src );
                    }elseif( $type == "gif" ){
                            $srcImage = imageCreateFromGif( $src );
                    }
            }

            if( $srcWidth > $srcHeight ){
                    // 横長画像
                    if( $new_width < $srcWidth ){
                            $height = $srcHeight * $new_width / $srcWidth;
                            $newImage = imageCreateTrueColor( $new_width, $height );
                            imageCopyResampled( $newImage, $srcImage, 0, 0, 0, 0, $new_width, $height, $srcWidth, $srcHeight );
                            ImageJPEG($newImage, $dest, 90);
                            imageDestroy( $srcImage );

                    }else{
                            // 小さい画像だったらそのままコピー
                            copy( $src, $dest );
                    }
            }else{
                    // 縦長画像
                    if( $new_height < $srcHeight ){
                            $width = $srcWidth * $new_height / $srcHeight;
                            $newImage = imageCreateTrueColor( $width, $new_height );
                            imageCopyResampled( $newImage, $srcImage, 0, 0, 0, 0, $width, $new_height, $srcWidth, $srcHeight );
                            ImageJPEG($newImage, $dest, 90);
                            imageDestroy( $srcImage );

                    }else{
                            // 小さい画像だったらそのままコピー
                            copy( $src, $dest );
                    }
            }
            return;
    }
    
    
    
    /*
     * 公開側
     */
    public function getDisplayTopList($site_id, $category_id = '')
    {
        $setting = $this->getSetting($site_id);
        $list    = array();

        $db = new Model_DB();                
        $sql = "SELECT *
                FROM {$this->table_name} N
                LEFT JOIN {$this->category_table_name} C ON N.id = C.item_id
                WHERE site_id = '{$site_id}' and status = 1 and
                      (st_time is null or st_time <= current_timestamp or st_time = '0000-00-00 00:00:00') and
                      (ed_time is null or ed_time > current_timestamp or ed_time = '0000-00-00 00:00:00') ";
        if($category_id != '')
        {
            if(is_array($category_id))
            {
                foreach($category_id as $one)
                {
                    if(is_array($one)) return false;
                    $tmp[] = $db->escape($one);
                }
                $sql .= "and C.category_id in ('".implode("','", $tmp)."') ";
            }
            else
            {
                $sql .= "and C.category_id = '{$db->escape($category_id)}' ";
            }
        }
            
        $sql .= "ORDER BY {$setting['sort_item']} desc limit {$setting['top_nums1']}";

        $db->query($sql);
        while($res = $db->fetch()){
            $row = array();
            $row['id'] = $res['id'];
            $row['type'] = $res['type'];
            $row['url'] = $res['url'];
            foreach($setting['top_items'] as $key){
                if (isset($res[$key])){
                    $row[$key] = $res[$key];
                }
                
                if($key == "thumb")
                {
                    $db2 = new Model_DB();
                    $sql = sprintf("SELECT * FROM D_IMAGE WHERE func = %u and id = %u ORDER BY order_num", $this->config['id'], $row['id'] );
                    $db2->query( $sql );
                    if( $db2->num_rows() ){
                        while( $tmp = $db2->fetch() ){
                            $row[$key][] = "/seisansha/site_0001/item/thumb/thumb_".$tmp['filename'];
                        }
                    }
                }
            }
            $list[] = $row;
        }

        return $list;
    }
    
    public function getDisplayList($site_id, $category_id = '')
    {
        $setting = $this->getSetting($site_id);
        $list    = array();

        $db = new Model_DB();                
        $sql = "SELECT *
                FROM {$this->table_name} N
                LEFT JOIN {$this->category_table_name} C ON N.id = C.item_id
                WHERE site_id = '{$site_id}' and status = 1 and
                      (st_time is null or st_time <= current_timestamp or st_time = '0000-00-00 00:00:00') and
                      (ed_time is null or ed_time > current_timestamp or ed_time = '0000-00-00 00:00:00') ";
        if($category_id != '')
        {
            if(is_array($category_id))
            {
                foreach($category_id as $one)
                {
                    if(is_array($one)) return false;
                    $tmp[] = $db->escape($one);
                }
                $sql .= "and C.category_id in ('".implode("','", $tmp)."') ";
            }
            else
            {
                $sql .= "and C.category_id = '{$db->escape($category_id)}' ";
            }
        }
            
        $sql .= "ORDER BY {$setting['sort_item']} desc limit {$setting['list_nums']}";
        
        $db->query($sql);
        while($res = $db->fetch()){
            $row = array();
            $row['id'] = $res['id'];
            $row['type'] = $res['type'];
            $row['url'] = $res['url'];
            foreach($setting['list_items'] as $key){
                if (isset($res[$key])){
                    $row[$key] = $res[$key];
                }
                
                if($key == "thumb")
                {
                    $db2 = new Model_DB();
                    $sql = sprintf("SELECT * FROM D_IMAGE WHERE func = %u and id = %u ORDER BY order_num", $this->config['id'], $row['id'] );
                    $db2->query( $sql );
                    if( $db2->num_rows() ){
                        while( $tmp = $db2->fetch() ){
                            //$row[$key][] = $this->getThumbDir()."thumb_".$tmp['filename'];
                            //$row[$key][$tmp['order_num']] = "/seisansha/site_0001/item/thumb/thumb_".$tmp['filename'];
                            $row[$key][] = "/seisansha/site_0001/item/thumb/thumb_".$tmp['filename'];
                        }
                    }
                }
            }
            $list[] = $row;
        }

        return $list;
    }
}
?>